package com.hi.hiparty.entity.param;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;


import com.hi.hiparty.entity.UserInfo;
import com.hi.hiparty.util.StringUtils;

public class ParamUtil {
	public static Map<Class<?>,Map<Field,Validate>> fMap = new HashMap<Class<?>,Map<Field,Validate>>();
	public static Map<Class<?>,Map<String,Field>> nfMap = new HashMap<Class<?>,Map<String,Field>>();
	static{
		register(UserInfo.class);
	}
	private static void register(Class<?> clz){
		Map<Field,Validate> m = new HashMap<Field,Validate>();
		Map<String,Field> n = new HashMap<String,Field>();
		Field[] fields = clz.getDeclaredFields();
		for(Field f:fields){
			f.setAccessible(true);
			Validate v =f.getAnnotation(Validate.class);
			if(null!=v){
				m.put(f, v);
			}
			n.put(f.getName(), f);
		}
		fMap.put(clz, m);
		nfMap.put(clz, n);
	}
	public void checkField(Object obj,Class<?> clz){
		Map<Field,Validate> m = fMap.get(clz);
		if(null == m) return;
		for(Field f:m.keySet()){
			Validate v = m.get(f);
			checkFeild(f,v,obj);
		} 
	}
	/**
	 * @param f
	 * @param v
	 * @param obj
	 */
	public static boolean checkFeild(Field f,Validate v,Object obj){
		Object value = null;
		try {
			value = f.get(obj);
		} catch (Exception e) {
			return false;
		}
		if(v.required()&&null==value){
			return false;
		}
		if (null != value && v.type().equalsIgnoreCase("string")
				&& !v.format().isEmpty()) {
			if (!value.toString().matches(v.format())) {
				return false;
			}
		}
		if (v.type().equalsIgnoreCase("number")) {
			//要修改
			String str = value.toString();
			str = str.charAt(0) == '-' ? str.substring(1, str.length()) : str;
			String[] str2 = str.split(".");
			try {
				if(str2.length == 1){
					Integer.valueOf(str2[0]);
				}
				if(str2.length == 2){
					Integer.valueOf(str2[0]);
					Integer.valueOf(str2[1]);
				}
			}catch(Exception e){
				return false;
			}	
		}
		return true;
	}
	/**
	 * 
	 * @param obj
	 * @param clz
	 * @return
	 */
	public static String getGetMethodParams(Object obj,Class<?> clz){
		Map<Field,Validate> m = fMap.get(clz);
		if(null == m) return "";
		StringBuilder sb = new StringBuilder();
		for(Field f:m.keySet()){
			try {
				Validate v = m.get(f);
				Object value = f.get(obj);
				String name = v.name();
				if (!name.isEmpty() && value != null && value.toString().length() > 0)
					if(v.type().equalsIgnoreCase("date")){
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
						if(!v.format().isEmpty()){
							dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						}
						sb.append(name).append("=").append(dateFormat.format(value)).append("&");
					}else{
						sb.append(name).append("=").append(value.toString()).append("&");
					}
			} catch (Exception e) {
				return "";
			}
		} 
		return sb.toString();
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String,String> getPostMethodParams(Object obj,Class<?> clz){
		Map<Field,Validate> m = fMap.get(clz);
		if(null == m) return Collections.EMPTY_MAP;
		Map<String,String> params = new HashMap<String,String>();
		for(Field f:m.keySet()){
			try {
				Validate v = m.get(f);
				Object value = f.get(obj);
				String name = v.name();
				if (!name.isEmpty() && value != null && value.toString().trim().length() > 0)
					if(v.type().equalsIgnoreCase("date")){
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
						if(!v.format().isEmpty()){
							dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						}
						params.put(name, dateFormat.format(value));	
					}else{
						params.put(name, value.toString());	
					}
			} catch (Exception e) {
				return Collections.EMPTY_MAP;
			}
		}
		return params;
	}
	
	/**
	 * 目前支持字符和int型
	 * @param obj
	 * @param clz
	 * @param json
	 */
	public static void fromJSONO2Object(Object obj,Class<?> clz,JSONObject json){
		Map<Field,Validate> m = fMap.get(clz);
		for(Field f:m.keySet()){
			try {
				Validate v = m.get(f);
				//字符串
				if(StringUtils.isNotBlank(v.type())
						&&v.type().equalsIgnoreCase("string")){
					String value = json.getString(v.name());
					if(StringUtils.isNotBlank(value))
					f.set(obj, value);
					continue;
				}
				//integer
				if(StringUtils.isNotBlank(v.type())
						&&v.type().equalsIgnoreCase("int")){
					Integer value = (Integer)json.get(v.name());
					if(null!=value){
						f.set(obj, value);
					}
					continue;
				}
				//date 有警告信息
				if(StringUtils.isNotBlank(v.type())
						&&v.type().equalsIgnoreCase("date")){
//					Map<String,Field> dm = nfMap.get(Date.class);
//					Iterator<String> it =json.keys();
//					while(it.hasNext()){
//						String e = it.next();
//						dm.get(json.get(e)).set(obj, json.get(e));
//					}
					continue;
				}
		    }catch(Exception e){
		    	continue;
		    }
		} 
	}
}
